#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    websocket = new QWebSocket();
    connect(websocket,SIGNAL(connected()),this,SLOT(onConnected()),Qt::UniqueConnection);
    connect(websocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()),Qt::UniqueConnection);
    connect(websocket, SIGNAL(binaryMessageReceived(QByteArray)), this, SLOT(onBinaryMessageReceived(QByteArray)),Qt::UniqueConnection);
    connect(websocket, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString)),Qt::UniqueConnection);

    ui->lineEdit->setText(url);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onDisconnected()
{
    qDebug()<<"websocket is disconnected";
    ui->consoleText->append(QString("[websocket] websocket 断开"));
    isconnect = false;
    ui->pushButton->setText("链接");
    //    reconnect(); // 这里可以设自动重连
}
void MainWindow::onConnected()
{
    qDebug()<<"connect successful";
    ui->consoleText->append(QString("[websocket] websocket 链接成功"));
    isconnect = true;
    ui->pushButton->setText("断开");
}
void MainWindow::onBinaryMessageReceived(QByteArray message)
{
    qDebug() << "回传";
}

void MainWindow::onTextMessageReceived(QString message)
{
    qDebug() << "回传text";
    ui->consoleText->append(QString("[服务端] ")+message);
}
void MainWindow::reconnect()
{
    qDebug()<<"websocket reconnected";
    websocket->abort();
    websocket->open(QUrl(url));
}

void MainWindow::on_pushButton_clicked()
{
    // 是否链接
    if(!isconnect)
    {
        // 链接
        url = ui->lineEdit->text();
        websocket->open(QUrl(url));
        ui->consoleText->append(QString("[websocket] ")+QString(url));
    }else{
        // 断开
        websocket->close();
    }

}

void MainWindow::on_pushButton_2_clicked()
{
    QString message =  ui->sendTextEdit->text();
    websocket->sendTextMessage(message);
    ui->consoleText->append(QString("[客户端] 往服务端发送：")+message);
    ui->sendTextEdit->clear();
}
